package com.sunrise.generico.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.PasswordEncoder;

public class SecurityUtil implements PasswordEncoder {

	public static String criptografar(String senha) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] digest = md.digest(senha.getBytes());

			StringBuilder hexString = new StringBuilder();
			for (byte b : digest) {
				hexString.append(String.format("%02X", 0xFF & b));
			}
			String result = hexString.toString();

			return result;
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	public static String gerarToken() {
		String token = RandomStringUtils.random(20, 0, 0, true, true, null,
				new SecureRandom());
		return token;
	}

	public static boolean validarTamanhoSenha(String senha) {
		if (senha.length() < 8) {
			return false;
		}
		return true;
	}

	@Override
	public String encodePassword(String rawPass, Object salt)
			throws DataAccessException {
		return null;
	}

	@Override
	public boolean isPasswordValid(String encPass, String rawPass, Object salt)
			throws DataAccessException {
		rawPass = criptografar(rawPass);
		return equals(encPass, rawPass);
	}

	private boolean equals(String expected, String actual) {
		byte[] expectedBytes = bytesUtf8(expected);
		byte[] actualBytes = bytesUtf8(actual);
		int expectedLength = expectedBytes == null ? -1 : expectedBytes.length;
		int actualLength = actualBytes == null ? -1 : actualBytes.length;
		if (expectedLength != actualLength) {
			return false;
		}

		int result = 0;
		for (int i = 0; i < expectedLength; i++) {
			result |= expectedBytes[i] ^ actualBytes[i];
		}
		return result == 0;
	}

	private static byte[] bytesUtf8(String s) {
		if (s == null) {
			return null;
		}
		try {
			return s.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(
					"Could not get bytes in UTF-8 format", e);
		}
	}
	
	
	public static String randomString(int length) {
		char[] charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789zxcvbnmasdfghjklqwertyuiop".toCharArray();
		Random random = new SecureRandom();
		char[] result = new char[length];
		for (int i = 0; i < result.length; i++) {
			int randomCharIndex = random.nextInt(charSet.length);
			result[i] = charSet[randomCharIndex];
		}
		return new String(result);
	}

}
